﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SCMS.Model;
using System.Transactions;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.NotificationsManager;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace SCMS.CoreBusinessLogic._GoodsReceivedNote
{
    public class GoodsReceivedNoteService : IGoodsReceivedNoteService
    {

        public bool SaveGRN(List<POItemsView> GRNItemColl, GoodsReceivedNote GRNEntity)
        {
            using (var dbContext = new SCMSEntities())
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        dbContext.GoodsReceivedNotes.AddObject(GRNEntity);
                        foreach (POItemsView item in GRNItemColl)
                        {
                            var newEntity = new GoodsReceivedNoteItem()
                            {
                                Id = Guid.NewGuid(),
                                GoodsReceivedNoteId = GRNEntity.Id,
                                PurchaseOrderItemId = item.POItemId,
                                QuantityDelivered = item.QtyDelivered,
                                QuantityDamaged = item.QtyDamaged,
                                Comments = item.comments,
                            };
                            dbContext.GoodsReceivedNoteItems.AddObject(newEntity);
                        }
                        if ((dbContext.SaveChanges() > 0))
                        {
                            //NotificationServiceMail.SendNotification(NotificationServiceMail.GetApproverEmailAddress(1, NotifcationHelper.spmCode), NotifcationHelper.spMsgBody, NotifcationHelper.spsubject);
                            scope.Complete();
                            return true;
                        }
                        else { scope.Dispose(); return false; }

                    }
                    catch (Exception ex)
                    {
                        scope.Dispose();
                        throw ex;
                    }
                }
            }
        }

        public bool IsGRNVerified(Guid GRNId, List<Model.GoodsReceivedNoteItem> itmz, Guid CPId)
        {
            using (var db = new SCMSEntities())
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    foreach (GoodsReceivedNoteItem item in itmz)
                    {
                        GoodsReceivedNoteItem grit = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == item.Id);
                        if (db.Inventories.Count(p => p.ItemId == grit.PurchaseOrderItem.OrderRequestItem.Item.Id && p.WareHouseId == grit.GoodsReceivedNote.WareHouseId) > 0)
                        {
                            if (grit.PurchaseOrderItem.OrderRequestItem.Item.ItemCategory.CategoryCode == "C")
                            {
                                Model.Inventory invt = db.Inventories.FirstOrDefault(p => p.ItemId == grit.PurchaseOrderItem.OrderRequestItem.Item.Id && p.WareHouseId == grit.GoodsReceivedNote.WareHouseId);
                                invt.Quantity += (long)item.QuantityDelivered;
                                db.ObjectStateManager.ChangeObjectState(invt, System.Data.EntityState.Modified);
                            }
                        }
                        else
                        {
                            long qty = 0;
                            if (grit.PurchaseOrderItem.OrderRequestItem.Item.ItemCategory.CategoryCode == "C") qty = (long)item.QuantityDelivered;
                            Model.Inventory newinvetoryEntity =
                                new Model.Inventory() { Id = Guid.NewGuid(), ItemId = grit.PurchaseOrderItem.OrderRequestItem.Item.Id, Quantity = qty, CountryProgrammeId = CPId, WareHouseId = (Guid)grit.GoodsReceivedNote.WareHouseId };
                            db.Inventories.AddObject(newinvetoryEntity);
                        }
                        Model.GoodsReceivedNoteItem grnitm = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == item.Id);
                        grnitm.QuantityDamaged = item.QuantityDamaged; grnitm.QuantityDelivered = item.QuantityDelivered;
                        db.ObjectStateManager.ChangeObjectState(grnitm, System.Data.EntityState.Modified);
                    }
                    Model.GoodsReceivedNote grn = db.GoodsReceivedNotes.FirstOrDefault(p => p.Id == GRNId);
                    grn.Verified = true;
                    db.ObjectStateManager.ChangeObjectState(grn, System.Data.EntityState.Modified);
                    if (db.SaveChanges() > 0) { scope.Complete(); return true; } else { scope.Dispose(); return false; }
                    //return db.SaveChanges() > 0 ? true : false; 
                }
            }
        }

        public bool IsAssetRegistered(Model.Asset assetEntity, Guid cpId)
        {
            using (var db = new SCMSEntities())
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        assetEntity.IsAssigned = false;
                        assetEntity.Id = Guid.NewGuid();
                        //if (assetEntity.UseLifeSpan)
                        //    assetEntity.DepreciationType = "Straight Line";
                        db.Assets.AddObject(assetEntity);
                        if (db.Inventories.Count(p => p.ItemId == assetEntity.ItemId && p.WareHouseId == assetEntity.CurrentWareHouseId) > 0)
                        {
                            Model.Inventory invt = db.Inventories.FirstOrDefault(p => p.ItemId == assetEntity.ItemId && p.WareHouseId == assetEntity.CurrentWareHouseId);
                            invt.Quantity += 1;
                            db.ObjectStateManager.ChangeObjectState(invt, System.Data.EntityState.Modified);
                        }
                        else
                        {
                            Model.Inventory newinvetoryEntity = new Model.Inventory() { Id = Guid.NewGuid(), ItemId = (Guid)assetEntity.ItemId, Quantity = 1, CountryProgrammeId = cpId, WareHouseId = (Guid)assetEntity.CurrentWareHouseId };
                            db.Inventories.AddObject(newinvetoryEntity);
                        }

                        if (assetEntity.IsFleet)
                            db.FleetDetails.AddObject(new FleetDetail() { Id = Guid.NewGuid(), CountryProgrammeId = assetEntity.CountryProgramId, AssetId = assetEntity.Id, IssueDate = DateTime.Now });

                        if (assetEntity.DepreciationType == "Zero Percentage")
                        {
                            if (!(db.SaveChanges() > 0)) { scope.Dispose(); return false; } else { scope.Complete(); return true; }
                        }
                        else
                            assetEntity.DepreciationPeriods = assetEntity.Lifespan * 12;
                        return this.IsDepreciationComputed(db, scope, assetEntity);
                    }
                    catch (Exception ex) { scope.Dispose(); throw ex; }
                }
            }
        }

        private bool IsDepreciationComputed(SCMSEntities db, TransactionScope scope, Asset assetEntity)
        {
            //var firstdateinMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-1);
            //var lastdateinMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);
            //float purchasePrc = (float)gitm.PurchaseOrderItem.UnitPrice
            Model.Depreciation deprEntity = null;
            Model.GoodsReceivedNoteItem gitm = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == assetEntity.GoodsReceivedNoteItemId);
            float purchasePrc = (float)assetEntity.PurchaseValue, percentageDepr = (float)assetEntity.PercentageDepr, accAnnualDepr = 0;
            float annualDepr = 0, monthlyDepr, netbookValue = purchasePrc, accumulatedDepr = 0, salvagevalue = (float)assetEntity.SalvageValue;
            int periodcount = 0, monthcount = 0, numberOfYears = 0;

            if (assetEntity.DepreciationType == "Reducing Balance")
                monthlyDepr = ReducingBalance(db, assetEntity, ref deprEntity, percentageDepr, ref accAnnualDepr, ref annualDepr, ref netbookValue, ref accumulatedDepr, salvagevalue, ref periodcount, ref monthcount, ref numberOfYears);
            else
                monthlyDepr = StraightLine(db, assetEntity, ref deprEntity, purchasePrc, percentageDepr, ref accAnnualDepr, ref annualDepr, ref netbookValue, ref accumulatedDepr, salvagevalue, ref periodcount, ref monthcount);

            if (!(db.SaveChanges() > 0)) { scope.Dispose(); return false; }
            scope.Complete(); return true;
        }

        private static float ReducingBalance(SCMSEntities db, Asset assetEntity, ref Model.Depreciation deprEntity, float percentageDepr, ref float accAnnualDepr, ref float annualDepr, ref float netbookValue, ref float accumulatedDepr, float salvagevalue, ref int periodcount, ref int monthcount, ref int numberOfYears)
        {
            float monthlyDepr;
            while (true)
            {
                annualDepr = ((netbookValue - salvagevalue) * (percentageDepr / 100));
                monthlyDepr = annualDepr / 12; numberOfYears++;

                if (assetEntity.UseLifeSpan)
                { if (numberOfYears > assetEntity.Lifespan) break; }
                else { if (annualDepr <= 12) break; }

                do
                {
                    monthcount++; periodcount++;
                    accumulatedDepr += monthlyDepr;
                    accAnnualDepr += monthlyDepr;
                    netbookValue -= monthlyDepr;
                    deprEntity = new Depreciation();
                    deprEntity.Id = Guid.NewGuid();
                    deprEntity.AssetId = assetEntity.Id;
                    deprEntity.Period = periodcount;
                    deprEntity.NetbookValue = netbookValue;
                    deprEntity.AccDepreciation = accumulatedDepr;
                    deprEntity.MonthlyDepreciation = monthlyDepr;
                    deprEntity.AnnualDepreciation = accAnnualDepr;
                    deprEntity.Date = new DateTime(DateTime.Now.AddMonths(periodcount).Year, DateTime.Now.AddMonths(periodcount).Month, 1).AddDays(-1);
                    db.Depreciations.AddObject(deprEntity);

                } while (monthcount <= 11); monthcount = 0; accAnnualDepr = 0;

            }
            return monthlyDepr;
        }

        private static float StraightLine(SCMSEntities db, Asset assetEntity, ref Model.Depreciation deprEntity, float purchasePrc, float percentageDepr, ref float accAnnualDepr, ref float annualDepr, ref float netbookValue, ref float accumulatedDepr, float salvagevalue, ref int periodcount, ref int monthcount)
        {
            float monthlyDepr;
            while (true)
            {

                if (assetEntity.UseLifeSpan)
                    annualDepr = (float)((float)(purchasePrc - (float)assetEntity.SalvageValue) / assetEntity.Lifespan);
                else annualDepr = (float)((float)(purchasePrc - (float)assetEntity.SalvageValue) * (percentageDepr / 100));
                periodcount++; monthcount++;
                monthlyDepr = annualDepr / 12;
                accumulatedDepr += monthlyDepr;
                netbookValue -= monthlyDepr;
                accAnnualDepr += monthlyDepr;

                deprEntity = new Depreciation();
                deprEntity.Id = Guid.NewGuid();
                deprEntity.AssetId = assetEntity.Id;
                deprEntity.Period = periodcount;
                deprEntity.NetbookValue = netbookValue;
                deprEntity.AccDepreciation = accumulatedDepr;
                deprEntity.MonthlyDepreciation = monthlyDepr;
                deprEntity.AnnualDepreciation = accAnnualDepr;
                deprEntity.Date = new DateTime(DateTime.Now.AddMonths(periodcount).Year, DateTime.Now.AddMonths(periodcount).Month, 1).AddDays(-1);
                db.Depreciations.AddObject(deprEntity);
                if (monthcount == 12) { monthcount = 0; accAnnualDepr = 0; }
                if (Math.Round(netbookValue) <= Math.Round(salvagevalue)) break;
            }
            return monthlyDepr;
        }

        public bool IsInventoryUpdated(Inventory InventEntity)
        {
            using (var db = new SCMSEntities())
            {
                if (db.Inventories.Count(p => p.ItemId == InventEntity.ItemId && p.WareHouseId == InventEntity.WareHouseId) > 0)
                {
                    Model.Inventory invt = db.Inventories.FirstOrDefault(p => p.ItemId == InventEntity.ItemId && p.WareHouseId == InventEntity.WareHouseId);
                    invt.Quantity += (long)InventEntity.Quantity;
                    db.ObjectStateManager.ChangeObjectState(invt, System.Data.EntityState.Modified);
                }
                else
                {
                    Model.Inventory newinvetoryEntity = new Model.Inventory() { Id = Guid.NewGuid(), ItemId = InventEntity.ItemId, Quantity = (long)InventEntity.Quantity, CountryProgrammeId = InventEntity.CountryProgrammeId, WareHouseId = InventEntity.WareHouseId };
                    db.Inventories.AddObject(newinvetoryEntity);
                }
                return db.SaveChanges() > 0 ? true : false;
            }
        }

        public bool IsAssetDisposed(Model.Asset AssetEntity)
        {
            using (var db = new SCMSEntities())
            {
                Model.Asset aset = db.Assets.FirstOrDefault(p => p.Id == AssetEntity.Id);
                aset.IsDesposed = true;
                aset.ActionType = AssetEntity.ActionType;
                db.ObjectStateManager.ChangeObjectState(aset, System.Data.EntityState.Modified);

                Model.Inventory inv = db.Inventories.FirstOrDefault(p => p.ItemId == aset.ItemId & p.WareHouseId == aset.CurrentWareHouseId);
                inv.Quantity -= 1;
                db.ObjectStateManager.ChangeObjectState(inv, System.Data.EntityState.Modified);
                return db.SaveChanges() > 0 ? true : false;
            }
        }

        public bool IsAssetStateChanged(Model.AssetManagment Entity)
        {
            using (var db = new SCMSEntities())
            {
                db.AssetManagments.AddObject(Entity);

                Model.Asset aset = db.Assets.FirstOrDefault(p => p.Id == Entity.AssetId);
                aset.IsAssetStateChanged = true;
                if (Entity.currentProjectId != null)
                    aset.CurrentProjectDonorId = Entity.currentProjectId;
                db.ObjectStateManager.ChangeObjectState(aset, System.Data.EntityState.Modified);
                return db.SaveChanges() > 0 ? true : false;
            }
        }

        public List<Model.GoodsReceivedNoteItem> GetGRNItems(Guid GRNId)
        {
            using (var db = new SCMSEntities())
            {
                List<GoodsReceivedNoteItem> grnitems = db.GoodsReceivedNoteItems.Where(p => p.GoodsReceivedNoteId == GRNId).ToList();
                foreach (GoodsReceivedNoteItem item in grnitems)
                {
                    PurchaseOrderItem poitm = item.PurchaseOrderItem;
                    OrderRequestItem oritm = poitm.OrderRequestItem;
                    Item i = oritm.Item;
                    UnitOfMeasure u = i.UnitOfMeasure;
                }
                return grnitems;
            }
        }

        public List<Model.GoodsReceivedNoteItem> GetRegisteredAssets(Guid GRNId)
        {
            using (var db = new SCMSEntities())
            {
                List<Model.GoodsReceivedNoteItem> grnitems = new List<GoodsReceivedNoteItem>(); ;
                foreach (GoodsReceivedNoteItem item in db.GoodsReceivedNoteItems.Where(p => p.GoodsReceivedNoteId == GRNId).ToList())
                    if (db.Assets.Count(p => p.GoodsReceivedNoteItemId == item.Id) > 0) grnitems.Add(item);

                foreach (GoodsReceivedNoteItem item in grnitems)
                {
                    PurchaseOrderItem poitm = item.PurchaseOrderItem;
                    OrderRequestItem oritm = poitm.OrderRequestItem;
                    Item i = oritm.Item;
                    UnitOfMeasure u = i.UnitOfMeasure;
                    EntityCollection<Model.Asset> a = item.Assets;
                    foreach (Model.Asset ast in a)
                    {
                        Model.ProjectDonor pd = ast.ProjectDonor;
                        Model.Project p = pd.Project;
                        Model.WareHouse wh = ast.WareHouse;
                    }
                }
                return grnitems;
            }
        }

        public List<Model.CountrySubOffice> GetCountrySubOffices(Guid cpid)
        {
            using (var db = new SCMSEntities())
            {
                return db.CountrySubOffices.Where(p => p.CountryProgrammeId == cpid).OrderBy(c => c.Name).ToList();
            }
        }

        public List<Model.WareHouse> GetSubOfficeWareHouses(Guid countrysubofficeId)
        {
            using (var db = new SCMSEntities())
            {
                return db.WareHouses.Where(p => p.SubOfficeId == countrysubofficeId).OrderBy(c => c.Name).ToList();
            }
        }

        public List<Model.PurchaseOrder> GetGRNPurchaseOrders(Guid countryProgId)
        {
            using (var context = new SCMSEntities())
            {
                List<Model.PurchaseOrder> pos = new List<Model.PurchaseOrder>();
                foreach (var PO in context.PurchaseOrders.Where(p => p.CountryProgrammeId == countryProgId && p.IsAuthorized == true).ToList())
                {
                    foreach (var POitem in PO.PurchaseOrderItems)
                    {
                        if (POitem.Quantity > POitem.GoodsReceivedNoteItems.Where(p => p.PurchaseOrderItemId == POitem.Id).Sum(a => a.QuantityDelivered))
                        { pos.Add(POitem.PurchaseOrder); break; }
                    }
                }
                return pos;
            }
        }

        public List<POItemsView> GetPOItemsDetails(Guid POId)
        {
            List<POItemsView> poitemList = new List<POItemsView>();
            using (var dbContext = new SCMSEntities())
            {
                poitemList = (from po in dbContext.PurchaseOrders
                              join poit in dbContext.PurchaseOrderItems on po.Id equals poit.PurchaseOrderId
                              join orIt in dbContext.OrderRequestItems on poit.OrderRequestItemId equals orIt.Id
                              join itm in dbContext.Items on orIt.ItemId equals itm.Id
                              where po.Id == POId &
                              poit.Quantity > (((int?)poit.GoodsReceivedNoteItems.Where(p => p.PurchaseOrderItemId == poit.Id).Sum(a => a.QuantityDelivered)) ?? 0)
                              select new POItemsView
                              {
                                  POItemId = poit.Id,
                                  ItemName = itm.Name,
                                  Description = itm.Description,
                                  QtyOrdered = poit.Quantity,
                                  PreviouslyReceived = (int?)dbContext.GoodsReceivedNoteItems.Where(p => p.PurchaseOrderItemId == poit.Id).Sum(a => a.QuantityDelivered) ?? 0,
                                  packs = dbContext.ItemPackages.Where(p => p.ItemId == itm.Id),
                                  unitOfMessure = itm.UnitOfMeasure.Code
                              }).ToList<POItemsView>();
            }
            return poitemList;
        }

        public Model.PurchaseOrder GetPO(Guid POid)
        {
            using (var dbContext = new SCMSEntities())
            {
                var po = dbContext.PurchaseOrders.FirstOrDefault(p => p.Id == POid);
                Model.Supplier s = po.Supplier;
                return po;
            }
        }

        public List<Model.GoodsReceivedNote> GetGRNs(Guid cpId)
        {
            using (var db = new SCMSEntities())
            {
                List<Model.GoodsReceivedNote> grnList = db.GoodsReceivedNotes.Where(p => p.CountryProgrammeId == cpId).OrderByDescending(g => g.PreparedOn).ToList();
                foreach (GoodsReceivedNote item in grnList)
                {
                    Model.Supplier s = item.Supplier;
                    Model.CountrySubOffice c = item.CountrySubOffice;
                    EntityCollection<GoodsReceivedNoteItem> grnItems = item.GoodsReceivedNoteItems;
                    foreach (GoodsReceivedNoteItem grnitem in grnItems)
                    {
                        Model.PurchaseOrderItem poit = grnitem.PurchaseOrderItem;
                        Model.PurchaseOrder po = poit.PurchaseOrder;
                        Model.OrderRequest or = po.OrderRequest;
                    }
                }
                return grnList;
            }
        }

        public List<Model.GoodsReceivedNoteItem> GetGRNAssetItems(Guid GRNId)
        {
            using (var db = new SCMSEntities())
            {
                List<GoodsReceivedNoteItem> grnitems = db.GoodsReceivedNoteItems.Where(p => p.GoodsReceivedNoteId == GRNId && p.PurchaseOrderItem.OrderRequestItem.Item.ItemCategory.CategoryCode == "A").ToList();
                foreach (GoodsReceivedNoteItem item in grnitems)
                {
                    PurchaseOrderItem poitm = item.PurchaseOrderItem;
                    OrderRequestItem oritm = poitm.OrderRequestItem;
                    Item i = oritm.Item;
                    UnitOfMeasure u = i.UnitOfMeasure;
                }
                return grnitems;
            }
        }

        public string GenerateAssetNo(Model.GoodsReceivedNoteItem GRNItem)
        {
            string code = GRNItem.PurchaseOrderItem.OrderRequestItem.OrderRequest.ProjectDonor.Donor.ShortName + "/";
            code += GRNItem.PurchaseOrderItem.OrderRequestItem.OrderRequest.ProjectDonor.Project.ShortName + "/";
            long count = 1;
            using (var dbContext = new SCMSEntities())
            {
                Model.Asset m = dbContext.Assets.OrderByDescending(p => p.Index).FirstOrDefault();
                if (m != null)
                    count = m.Index + 1;

                if (count < 10000)
                {
                    if (count < 10)
                        return code + "0000" + count;
                    if (count < 100 & count >= 10)
                        return code + "000" + count;
                    if (count < 1000 & count >= 100)
                        return code + "00" + count;
                    if (count < 10000 & count >= 1000)
                        return code + "0" + count;
                }
                return code + count;
            }
        }

        public string GenerateAssetNo(Guid ProjectDId)
        {
            using (var dbContext = new SCMSEntities())
            {
                Model.ProjectDonor pd = dbContext.ProjectDonors.FirstOrDefault(p => p.Id == ProjectDId);
                string code = pd.Donor.ShortName + "/";
                code += pd.Project.ShortName + "/";
                long count = 1;
                Model.Asset m = dbContext.Assets.OrderByDescending(p => p.Index).FirstOrDefault();
                if (m != null)
                    count = m.Index + 1;

                if (count < 10000)
                {
                    if (count < 10)
                        return code + "0000" + count;
                    if (count < 100 & count >= 10)
                        return code + "000" + count;
                    if (count < 1000 & count >= 100)
                        return code + "00" + count;
                    if (count < 10000 & count >= 1000)
                        return code + "0" + count;
                }
                return code + count;
            }
        }

        public string GenerateUniquNumber(CountryProgramme cp)
        {
            string code = "GRN/DRC/" + cp.Country.ShortName + "/";
            string refNumber = "";
            long count = 1;
            using (var dbContext = new SCMSEntities())
            {
                var total = dbContext.GoodsReceivedNotes.Where(p => p.CountryProgrammeId == cp.Id && p.IsSubmitted == true).Count();
                count = total;
                Model.GoodsReceivedNote m = null;
                do
                {
                    count++;
                    if (count < 10000)
                    {
                        if (count < 10)
                            refNumber = code + "0000" + count;
                        if (count < 100 & count >= 10)
                            refNumber = code + "000" + count;
                        if (count < 1000 & count >= 100)
                            refNumber = code + "00" + count;
                        if (count < 10000 & count >= 1000)
                            refNumber = code + "0" + count;
                    }
                    m = dbContext.GoodsReceivedNotes.FirstOrDefault(p => p.RefNumber == refNumber);
                } while (m != null);
                return refNumber;
            }
        }

        public List<GoodsReceivedNoteItem> GetUnregisteredGRNItems(Guid cpId)
        {
            using (var db = new SCMSEntities())
            {
                List<GoodsReceivedNoteItem> grnItemList = new List<GoodsReceivedNoteItem>();
                foreach (GoodsReceivedNoteItem item in db.GoodsReceivedNoteItems.Where(p => p.GoodsReceivedNote.Verified == true &
                    p.PurchaseOrderItem.OrderRequestItem.Item.ItemCategory.CategoryCode == "A" & p.GoodsReceivedNote.CountryProgrammeId == cpId).ToList())
                {
                    if (item.QuantityDelivered <= item.Assets.Count()) continue;
                    GoodsReceivedNote g = item.GoodsReceivedNote;
                    PurchaseOrderItem poitm = item.PurchaseOrderItem;
                    OrderRequestItem oritm = poitm.OrderRequestItem;
                    Item i = oritm.Item;
                    UnitOfMeasure u = i.UnitOfMeasure;
                    grnItemList.Add(item);

                }
                return grnItemList;
            }
        }

        public List<GoodsReceivedNote> GetGRNsForApproval(Staff currentStaff)
        {
            try
            {
                using (var context = new SCMSEntities())
                {
                    return context.GoodsReceivedNotes.Where(g => g.IsSubmitted == true && g.Verified == false && g.IsRejected == false && g.ReceptionApprovedBy == currentStaff.Id).ToList();
                }
            }
            catch (Exception ex)
            {
                return new List<Model.GoodsReceivedNote>();
            }
        }

        public GoodsReceivedNote GetGRNById(Guid id)
        {
            using (var context = new SCMSEntities())
            {
                var grn = context.GoodsReceivedNotes.FirstOrDefault(g => g.Id == id);
                if (grn.Staff != null)
                {
                    var person = grn.Staff.Person;
                    var desg = grn.Staff.Designation;
                }
                if (grn.Staff1 != null)
                {
                    var person = grn.Staff1.Person;
                    var desg = grn.Staff1.Designation;
                }
                return grn;
            }
        }

        public void UpdateGRN(GoodsReceivedNote grn)
        {
            using (var context = new SCMSEntities())
            {
                context.GoodsReceivedNotes.Attach(grn);
                context.ObjectStateManager.ChangeObjectState(grn, System.Data.EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteGRNById(Guid id)
        {
            using (var context = new SCMSEntities())
            {
                var grn = new GoodsReceivedNote { Id = id };
                context.GoodsReceivedNotes.Attach(grn);
                context.ObjectStateManager.ChangeObjectState(grn, System.Data.EntityState.Deleted);
                context.SaveChanges();
            }
        }
    }

    public class POItemsView
    {
        public Guid POItemId { get; set; }
        public string ItemName { get; set; }
        public string Description { get; set; }
        public int QtyOrdered { get; set; }
        [Required(ErrorMessage = "Required Field")]
        public decimal QtyDelivered { get; set; }
        [Required(ErrorMessage = "Required Field")]
        public decimal QtyDamaged { get; set; }
        public decimal PreviouslyReceived { get; set; }
        public string comments { get; set; }
        public string unitOfMessure { get; set; }
        public IEnumerable<Model.ItemPackage> packs { get; set; }
    }
}
